package conf

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"os"
	"os/signal"
	"path/filepath"
)

func WatchFile(watchFile string, call func(path string)) {
	// 创建文件监视器
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println(err)
		return
	}
	defer func(watcher *fsnotify.Watcher) {
		err = watcher.Close()
		if err != nil {
			return
		}
	}(watcher)

	// 监听操作系统信号
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, os.Interrupt)

	// 添加文件监视器
	// 可以监听文件，也可以监听目录
	err = filepath.Walk(watchFile, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			err = watcher.Add(path)
			if err != nil {
				fmt.Println(err)
			}
			//fmt.Println("Add", path)
		}
		return nil
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	// 等待文件变化或操作系统信号
	for {
		select {
		case event, ok := <-watcher.Events:
			if !ok {
				return
			}
			if event.Op&fsnotify.Write == fsnotify.Write {
				call(event.Name)
			}
		case err, ok := <-watcher.Errors:
			if !ok {
				return
			}
			fmt.Println("错误：", err)
		case <-sigs:
			fmt.Println("程序退出")
			return
		}
	}
}
